<?php
namespace app\index\controller;

class Login extends \think\Controller{
    public function index(){
        $get = $_GET;
        
        $wechatInfo = db("wechat")->find();
        
        if (empty($wechatInfo)) {
            $this->error('公众号异常，请稍后重试!');
            exit;
        }
	
        $redirect_domain = $wechatInfo['domain']; //登录完成后的回调域名
        if (!$redirect_domain) {
            $redirect_domain = $_SERVER['HTTP_HOST'];
        }
        
        $_controller = input('_controller'); //用户登录后要跳转的控制器方法
        $_action    =  input('_action');
        
        if (!isset($get['code'])) {
            $redirect_uri = "http://{$wechatInfo['domain']}/Index/Login/index";
            
            $state = '123';
            if ($_controller && $_action) {
                $state = $_controller . '_' . $_action ;
            }
            
            $getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wechatInfo['appid']}&redirect_uri=" . urlencode($redirect_uri) . "&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
            header("location:{$getCodeUrl}");
            exit;
        }
        
        $code = input("code");
        //获取access_token ,不能每次请求都去取一次
        $wechat_api = new \WechatApi($wechatInfo['appid'] , $wechatInfo['appsecret']);
        $access_token = $wechat_api->getAccessToken();
        
        //获取openid
        $get_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wechatInfo['appid']}&secret={$wechatInfo['appsecret']}&code={$code}&grant_type=authorization_code";
        $openidInfo = json_decode($this->https_request($get_openid_url) , true);
        
        $openid = $openidInfo['openid'];
        cookie("_openid", $openid);
        
        $jump = [];
      	
        if ($get['state'] != '123') {
            $jump = explode('_', $get['state']);
        }
        $controller = $jump[0] ? $jump[0] : 'Index';
        $action = $jump[1] ? $jump[1] : 'index';
        
        $url = url("{$controller}/{$action}@{$redirect_domain}");
       	header("location:" . $url);
        die;
    }

    public function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return ($output);
    }
}
